<template>
  <div class="login">
    <header>UNI-ADMIN</header>
    <el-form :model="users" ref="usersform" :rules="rules">
      <el-form-item prop="username">
        <el-input placeholder="请输入用户名" v-model="users.username"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          placeholder="请输入密码"
          v-model="users.password"
          type="password"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="success" style="width: 100%" @click="login" :loading="loading">
          <!-- 等于true时按钮变成登录中 否则就是登录 -->
          {{ loading ? "登录中···" : "登录" }}
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      users: {
        username: "admin",
        password: "admin",
      },
      rules: {
        username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      loading: false,
    };
  },
  created() {},
  mounted() {},
  methods: {
    login() {
      this.$refs.usersform.validate((valid) => {
        if (valid) {
          //成功
          // 登录成功是加载按钮转动
          this.loading = true;
          //   请求接口登录信息
          this.$axios
            .post("/admin/login", this.users)
            .then((res) => {
              // 登录成功后加载按钮暂停
              this.loading = false;
              // 登录成功后要做的
              // console.log(res)
              this.$message.success("登录成功");
              // 提示登陆成功 存储用户名和token信息
              let obj = {
                username: res.data.username,
                token: res.data.token,
              };
              this.$store.commit("login", obj);
              // 跳转
              this.$router.push("/");
            })
            .catch((error) => {
              // 登录失败后加载按钮暂停
              this.loading = false;
              // 登录失败后要做的
              // console.log(error.response.data);
              // 弹出错误提示
              this.$message.error(error.response.data.msg);
              return false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
  computed: {},
};
</script>

<style scoped lang="scss">
.login {
  width: 40%;
  border: 1px solid #ddd;
  border-radius: 5px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  header {
    width: 100%;
    line-height: 60px;
    font-size: 26px;
    text-align: center;
    font-weight: bold;
    border-bottom: 1px solid #ddd;
  }
  .el-form {
    width: 100%;
    padding: 20px;
    box-sizing: border-box;
  }
}
</style>
